package webSocketSockJs;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

/**
 * Description
 *
 * @author dyoon
 * @date 2018-06-29
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        //允许连接的域,只能以http或https开头，或者使用*号允许全部域名访问
        String[] allowsOrigins = {"http://www.localhost.com"};

        //WebSocket通道，
        //addHandler:注册端点/webSocketIMServer处理程序handler,是收集和消息分发中心。
        //setAllowedOrigins：限制域名，如果不限制则改成setAllowedOrigins(*)
        //addInterceptors:增加拦截器
        //一般很少用，一般使用withSockJS(),使接口支持SocketJS功能
        registry.addHandler(myHandler(),"/webSocketIMServer").setAllowedOrigins(allowsOrigins).addInterceptors(webSocketInterceptor());
        //SockJs通道，配置逻辑同上，只是多了withSockJS()方法，使其支持SocketJS功能
        registry.addHandler(myHandler(), "/sockjs/webSocketIMServer").setAllowedOrigins(allowsOrigins).addInterceptors(webSocketInterceptor()).withSockJS();
    }
    @Bean
    public MyHandler myHandler() {
        return new MyHandler();
    }

    @Bean
    public WebSocketInterceptor webSocketInterceptor(){
        return new WebSocketInterceptor();
    }
}
